package org.goldfish.message_board01.servlets;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.util.List;

import org.goldfish.message_board01.entity.MessagePreview;
import org.goldfish.message_board01.services.MessageService;

//@WebServlet("/message")
public class MessageDetailServlet extends GFAbstractServlet {
    private MessageService messageService;

    @Override
    public void init() throws ServletException {
        messageService=new MessageService();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int messageId = Integer.parseInt(request.getParameter("id"));

        List<MessagePreview> messagePreviewsList = messageService.getAllMessagePreviews();
        messagePreviewsList.forEach(System.out::println);

        MessagePreview[] messagePreviews = new MessagePreview[1];
        messagePreviewsList.forEach(messagePreview -> {
            if (messagePreview.getId() == messageId) {
                messagePreviews[0] = messagePreview;
            }
        });
        request.setAttribute("messagePreview", messagePreviews[0]);

        List<String> messageDetails = messageService.getMessageDetails(messageId);
        request.setAttribute("messageDetails", messageDetails);
        RequestDispatcher dispatcher = request.getRequestDispatcher("messageDetail.jsp");
        dispatcher.forward(request, response);
    }

    @Override
    public void destroy() {
        messageService=null;
    }
}
